package top.liumiao.chatwx.utils;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.function.Consumer;

@EqualsAndHashCode(callSuper = false)
@Slf4j
@Data
public class BigModelNew {
    // 各版本的hostUrl及其对应的domian参数，具体可以参考接口文档 https://www.xfyun.cn/doc/spark/Web.html
    private String hostUrl;
    private String domain;
    private String appid;
    private String apiSecret;
    private String apiKey;

    private final Gson gson = new Gson();

    // 个性化参数
    private String userId = IdUtil.randomUUID();

    public BigModelNew(String hostUrl, String domain, String appid, String apiSecret, String apiKey, String userId) {
        if (hostUrl == null || domain == null || appid == null || apiSecret == null || apiKey == null) {
            throw new IllegalArgumentException("Required parameters cannot be null!");
        }
        this.hostUrl = hostUrl;
        this.domain = domain;
        this.appid = appid;
        this.apiSecret = apiSecret;
        this.apiKey = apiKey;
        this.userId = userId;
    }

    public void askStream(String question, Consumer<String> contentConsumer) throws Exception {
        // 设置问题
        String newQuestion = question;
        log.debug("设置问题: {}", newQuestion);

        // 构建鉴权url
        String authUrl = getAuthUrl(this.hostUrl, this.apiKey, this.apiSecret);
        OkHttpClient client = new OkHttpClient.Builder().build();
        String url = authUrl.replace("http://", "ws://").replace("https://", "wss://");
        Request request = new Request.Builder().url(url).build();
        log.debug("构建WebSocket URL: {}", url);

        // 创建WebSocket连接并发送请求
        CountDownLatch latch = new CountDownLatch(1);
        client.newWebSocket(request, new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                super.onOpen(webSocket, response);
                System.out.println("WebSocket connection opened.");
                log.debug("WebSocket 连接打开");
                MyThread myThread = new MyThread(webSocket, newQuestion, latch);
                myThread.start();
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                log.debug("接收到WebSocket消息: {}", text);
                JsonParse myJsonParse = gson.fromJson(text, JsonParse.class);
                if (myJsonParse.header.code != 0) {
                    System.out.println("发生错误，错误码为：" + myJsonParse.header.code);
                    System.out.println("本次请求的sid为：" + myJsonParse.header.sid);
                    webSocket.close(1000, "");
                    log.error("WebSocket 错误，错误码: {}, sid: {}", myJsonParse.header.code, myJsonParse.header.sid);
                }
                List<Text> textList = myJsonParse.payload.choices.text;
                for (Text temp : textList) {
                    String contentChunk = new String(temp.content.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
                    contentConsumer.accept(contentChunk); // 流式返回内容片段
                    log.debug("流式返回内容片段: {}", contentChunk);
                }
                if (myJsonParse.header.status == 2) {
                    latch.countDown(); // 结束标志
                    log.debug("WebSocket 消息处理完成");
                }
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                super.onFailure(webSocket, t, response);
                try {
                    if (response != null) {
                        int code = response.code();
                        System.out.println("onFailure code:" + code);
                        System.out.println("onFailure body:" + response.body().string());
                        if (101 != code) {
                            System.out.println("connection failed");
                            log.error("WebSocket 连接失败，code: {}, body: {}", code, response.body().string());
                            // 不要在这里退出程序，而是抛出异常
                            throw new IOException("WebSocket connection failed with code: " + code, t);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        // 等待模型回答完成
        latch.await();
        log.debug("等待模型回答完成");
    }

    public String ask(String question) throws Exception {
        // 设置问题
        String newQuestion = question;

        // 重置总答案
        final String[] totalAnswer = {""};

        // 构建鉴权url
        String authUrl = getAuthUrl(this.hostUrl, this.apiKey, this.apiSecret);
        OkHttpClient client = new OkHttpClient.Builder().build();
        String url = authUrl.replace("http://", "ws://").replace("https://", "wss://");
        Request request = new Request.Builder().url(url).build();

        // 创建WebSocket连接并发送请求
        CountDownLatch latch = new CountDownLatch(1);
        client.newWebSocket(request, new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                super.onOpen(webSocket, response);
                log.debug("大模型：");
                MyThread myThread = new MyThread(webSocket, newQuestion, latch);
                myThread.start();
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                JsonParse myJsonParse = gson.fromJson(text, JsonParse.class);
                if (myJsonParse.header.code != 0) {
                    System.out.println("发生错误，错误码为：" + myJsonParse.header.code);
                    System.out.println("本次请求的sid为：" + myJsonParse.header.sid);
                    webSocket.close(1000, "");
                }
                List<Text> textList = myJsonParse.payload.choices.text;
                for (Text temp : textList) {
                    System.out.print(new String(temp.content.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8));
                    totalAnswer[0] = totalAnswer[0] + temp.content;
                }
                if (myJsonParse.header.status == 2) {
                    System.out.println();
                    System.out.println("*************************************************************************************");
                    latch.countDown();
                }
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                super.onFailure(webSocket, t, response);
                try {
                    if (response != null) {
                        int code = response.code();
                        System.out.println("onFailure code:" + code);
                        System.out.println("onFailure body:" + response.body().string());
                        if (101 != code) {
                            System.out.println("connection failed");
                            // 不要在这里退出程序，而是抛出异常
                            throw new IOException("WebSocket connection failed with code: " + code, t);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        // 等待模型回答
        latch.await();

        // 返回模型的回答
        return totalAnswer[0];
    }

    public static boolean canAddHistory(List<RoleContent> historyList) {  // 由于历史记录最大上线1.2W左右，需要判断是能能加入历史
        int history_length = 0;
        for (RoleContent temp : historyList) {
            history_length = history_length + temp.content.length();
        }
        if (history_length > 12000) {
            historyList.remove(0);
            historyList.remove(1);
            historyList.remove(2);
            historyList.remove(3);
            historyList.remove(4);
            return false;
        } else {
            return true;
        }
    }

    // 修改后的 MyThread 构造函数
    class MyThread extends Thread {
        private WebSocket webSocket;
        private String newQuestion;
        private CountDownLatch latch;

        public MyThread(WebSocket webSocket, String newQuestion, CountDownLatch latch) {
            this.webSocket = webSocket;
            this.newQuestion = newQuestion;
            this.latch = latch;
            log.debug("MyThread 构造函数调用，newQuestion: {}", newQuestion);
        }

        @Override
        public void run() {
            try {
                JSONObject requestJson = new JSONObject();

                // header 参数
                JSONObject header = new JSONObject();
                header.put("app_id", appid);
                header.put("uid", UUID.randomUUID().toString().substring(0, 10));

                // parameter 参数
                JSONObject parameter = new JSONObject();
                JSONObject chat = new JSONObject();
                chat.put("domain", domain);
                chat.put("temperature", 0.5);
                chat.put("max_tokens", 4096);
                parameter.put("chat", chat);

                // payload 参数
                JSONObject payload = new JSONObject();
                JSONObject message = new JSONObject();
                JSONArray text = new JSONArray();

                // 最新问题
                RoleContent roleContent = new RoleContent();
                roleContent.role = "user";
                roleContent.content = newQuestion;
                text.add(JSON.toJSON(roleContent));

                message.put("text", text);
                payload.put("message", message);

                requestJson.put("header", header);
                requestJson.put("parameter", parameter);
                requestJson.put("payload", payload);
                log.debug("构建请求 JSON: {}", requestJson.toJSONString());

                // 发送请求
                if (webSocket != null) {
                    webSocket.send(requestJson.toString());
                    log.debug("WebSocket 发送请求: {}", requestJson.toString());
                } else {
                    throw new IllegalStateException("WebSocket is not initialized!");
                }

                // 等待回答完成
                while (true) {
                    Thread.sleep(200);
                    if (latch.getCount() == 0) {
                        break;
                    }
                }
                webSocket.close(1000, "");
                log.debug("WebSocket 关闭");
            } catch (Exception e) {
                e.printStackTrace();
                log.error("MyThread 运行时发生异常", e);
            }
        }
    }

    // 鉴权方法
    public String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        String preStr = "host: " + url.getHost() + "\n" +
                "date: " + date + "\n" +
                "GET " + url.getPath() + " HTTP/1.1";
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);

        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().//
                addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).//
                addQueryParameter("date", date).//
                addQueryParameter("host", url.getHost()).//
                build();

        return httpUrl.toString();
    }

    // 返回的json结果拆解
    class JsonParse {
        Header header;
        Payload payload;
    }

    class Header {
        int code;
        int status;
        String sid;
    }

    class Payload {
        Choices choices;
    }

    class Choices {
        List<Text> text;
    }

    class Text {
        String role;
        String content;
    }

    class RoleContent {
        String role;
        String content;

        public String getRole() {
            return role;
        }

        public void setRole(String role) {
            this.role = role;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }
    }
}
